var Skink; if (!Skink) Skink = {};

// Skink.verified = false;
Skink.startReloadTimer = function() {
    var refreshInterval = Skink.Prefs.getRefreshInterval();
    Skink.dump('started timer with refresh of ' + refreshInterval + ' msecs');
    reloadID = window.setInterval(Skink.UI.autoReloadCurrentTab, refreshInterval);
    return reloadID;
}

Skink.stopReloadTimer = function() {
    if (reloadID) {
        window.clearInterval(reloadID);
        Skink.dump('stopped timer');
    }
}

Skink.restartReloadTimer = function() {
    Skink.dump('trying to restart timer');
    Skink.stopReloadTimer();
    Skink.startReloadTimer();
}

Skink.createUserDirs = function() {
    var appStore = air.File.applicationStorageDirectory;
    var userThemesDir = appStore.resolvePath("userthemes/");
    userThemesDir.createDirectory()

    var userPluginsDir = appStore.resolvePath("userplugins/");
    userPluginsDir.createDirectory()

    var userSmileysDir = appStore.resolvePath("usersmileys/");
    userSmileysDir.createDirectory()

    air.trace(userThemesDir.nativePath);
    air.trace(userPluginsDir.nativePath);
    air.trace(userSmileysDir.nativePath);
};

/**
 * Bootstraps the app
 */
Skink.initialize = function() {
    air.trace('root init begin');

    // create user themes and plugins dirs if necessary
    Skink.createUserDirs();

    /***************************
	 * Load prefs
	 **************************/
    air.trace('init prefs');
    Skink.Prefs.init();

    air.trace('init Sections');
    Skink.Section.init();

    // turn on debugging
    if (Skink.Prefs.get('debug-enabled')) {
	    air.trace('Debug enabled');
        Skink.Debug.insertDebugScripts();
    }

    // Database initialization
    Skink.DB.init();

    air.NativeApplication.nativeApplication.autoExit = true;

    window.htmlLoader.manageCookies = false;
    window.htmlLoader.paintsDefaultBackground = false;
    window.htmlLoader.cacheResponse = true;
    window.htmlLoader.useCache = true;
    Skink.Sys.initUserAgentString();

    air.URLRequestDefaults.manageCookies = false;
    air.URLRequestDefaults.cacheResponse = true;
    air.URLRequestDefaults.useCache = true;

    Skink.Windows.makeSystrayIcon()

    // ***************************************************************
    // Keyboard shortcut handling
    // ***************************************************************
    Skink.Keyboard.setShortcuts();

    // insert theme CSS links
    Skink.Themes.init();

    /***************************
	 * Apply prefs
	 **************************/
    window.moveTo(Skink.Prefs.get('window-x'), Skink.Prefs.get('window-y'));
    window.resizeTo(Skink.Prefs.get('window-width'), Skink.Prefs.get('window-height'));
    $('#username').val(Skink.Prefs.getUser());
    $('#password').val(Skink.Prefs.getPass());

    /************************
	 * Other stuff to do when document is ready
	 ***********************/
    Skink.Windows.makeWindowVisible();
    Skink.dump('Made window visible');

    window.nativeWindow.visible = true;

    if (Skink.Prefs.get('window-minimizeatstartup')) {
        Skink.Windows.windowMinimize()
    }

    $('body').fadeIn(1000);

    Skink.UI.tabbedPanels = new Spry.Widget.TabbedPanels("tabs");

    Skink.UI.entryBox = new Spry.Widget.ValidationTextarea("entrybox", {
        maxChars: 140,
        counterType: "chars_remaining",
        counterId: 'chars-left-count',
        hint: Skink.Prefs.get('entryboxhint'),
        useCharacterMasking: true
    });

    Skink.UI.prefsCPG = new Spry.Widget.CollapsiblePanelGroup("prefsCPG", {
        contentIsOpen: false,
        duration: 200
    });

    $('#header-label').menu({
        copyClassAttr: true,
        addExpando: true,
        onClick: $.Menu.closeAll
    },
    '#mainMenuRoot');

    // $('.panelmenu form input[title="filter"]').hint();
    $('.TabbedPanelsTab').each(function(i) {
        this.title = this.title + '<br />Shortcut: <strong>CMD or CTRL+' + (parseInt(i) + 1) + '</strong>';
    });
    Skink.dump('Set shortcut info in tab titles');

    /*
		set-up window and app events
	*/
    window.nativeWindow.addEventListener(air.Event.EXITING, Skink.Windows.onWindowClose);
    // air.NativeApplication.nativeApplication.addEventListener(air.Event.EXITING, Skink.Windows.onAppExit);
    window.nativeWindow.addEventListener(air.Event.CLOSING, Skink.Windows.onWindowClose);
    window.nativeWindow.addEventListener(air.Event.ACTIVATE, Skink.Windows.onWindowActive);
    window.nativeWindow.addEventListener(air.NativeWindowBoundsEvent.RESIZE, Skink.Windows.onWindowResize);
    window.nativeWindow.addEventListener(air.NativeWindowBoundsEvent.MOVE, Skink.Windows.onWindowMove);
    window.nativeWindow.addEventListener(air.Event.DEACTIVATE, Skink.Windows.onWindowDeactivate);

    /*
		Initialize native menus
	*/
    Skink.Menus.initAll();

    /*
		Set up event delegation stuff
	*/
    Skink.Intercept.init();
	air.trace('intercepts initialised');

	air.trace('Getting rate limits...');
    if (Skink.Prefs.get('network-autoadjustrefreshinterval')) {
        Skink.Data.getRateLimitInfo(Skink.Prefs.setRateLimit);
    }

	air.trace('Checking load on startup...');
    if (Skink.Prefs.get('timeline-loadonstartup')) {
        $('#tab-search').trigger('click');
    }

    Skink.dump('ended document.ready()');
}